from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
# 专门用于模拟复杂的用户交互操作
from selenium.webdriver.common.action_chains import ActionChains

import time


# 设置浏览器、启动浏览器
def create_driver():
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_experimental_option("detach", True)
    driver_edge = webdriver.Edge(options=options)
    return driver_edge
driver = create_driver()

driver.get("https://www.bilibili.com/")
driver.maximize_window()
# 找到需要悬停的元素
el_hover = driver.find_element(By.XPATH, '//*[@id="i_cecream"]/div[2]/div[1]/div[1]/ul[1]/li[6]/a/span')

# 执行悬停操作
actions = ActionChains(driver)
actions.move_to_element(el_hover).perform()
print("鼠标停在了漫画上")
time.sleep(1)
# 执行点击操作
subel_hover = driver.find_element(By.XPATH, '//*[@id="i_cecream"]/div[2]/div[1]/div[1]/ul[1]/li[6]/div/div/div/div[2]/div[2]/div[1]')
actions.click(subel_hover).perform()
print("我已经点击了第一条链接")
# 目标：验证结果是否正确 [获取句柄、切换标签页]
# 获取全部标签页、句柄
handles = driver.window_handles
print(handles)
# 关闭之前标签页
driver.close()
# 通过句柄切换标签页
driver.switch_to.window(handles[1])
# 获取当前标签页的句柄
handles = driver.current_window_handle
print(f'当前控制标签页的句柄为：{handles}')
# 隐式等待
driver.implicitly_wait(30)
sub_title = driver.find_element(By.XPATH, '/html/body/div[1]/div/div[1]/div[2]/div[1]/div[2]/h1')
if sub_title.text == '不小心救了江湖公敌':
    print("测试成功！")
time.sleep(2)
driver.close()